package com.smbms.users.interceptor;

import com.alibaba.fastjson.JSON;
import com.smbms.commons.config.JwtConfig;
import com.smbms.commons.config.ResultCode;
import com.smbms.commons.config.ResultTool;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class IskLoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //接收token
        String token = request.getHeader("token");
        if (token == null) {
            //处理中文乱码
            response.setContentType("application/json;charset=utf-8");
            //获取out对象
            PrintWriter out = response.getWriter();
            //输出错误
            out.println(JSON.toJSONString(ResultTool.fail(ResultCode.USER_NOT_LOGIN)));
            return false;
        }
        //获取存的各种信息
        Claims claims = JwtConfig.parseJWT(token);
        int id = (int) claims.get("id");
        //设置使用String编码集
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setValueSerializer(stringSerializer);
        //从redis中取数据
        ValueOperations<String, String> value = redisTemplate.opsForValue();
        String result = value.get("token:" + id);
        if (result == null) {
            //处理中文乱码
            response.setContentType("application/json;charset=utf-8");
            //获取out对象
            PrintWriter out = response.getWriter();
            //输出错误
            out.println(JSON.toJSONString(ResultTool.fail(ResultCode.USER_NOT_LOGIN)));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
